package marble.views {

	import flash.events.Event;
	import flash.utils.setTimeout;
	
	import marble.model.Element;
	import marble.model.PlanProxy;
	
	import mx.controls.CheckBox;
	import mx.events.FlexEvent;
	import mx.rpc.events.ResultEvent;

	/**
	 * Customizable plan shown to a participant.
	 */
	public class ParticipantViewClass extends DefaultViewClass {

		[Bindable]
		public var showAll:CheckBox;

		private var userElements:Array;
		private var created:Boolean = false;

		override protected function onCreationComplete(event:FlexEvent):void {
			loadUserElements();
			setShowAllLabel();
		}
		
		override protected function updatePlan(addRem:Boolean = false, reg:Boolean = false):void {
			if (plan != null) {
				removeChild(plan);
			}
			plan = new PlanProxy(
				pagedElements(),
				getPageMonday(),
				minTime, maxTime,
				false, true,
				userElements
			);
			plan.width = 900;
			addChild(plan);
		}
		
		public function loadUserElements(forceRedraw:Boolean = false):void {
			facade.callRemote("getPlanElementsListByUserId", [facade.user_id],
				function (event:ResultEvent):void {
					userElements = new Array();
					for each (var obj:Object in event.result) {
						var el:Element = Element.create(obj);
						userElements.push(el);
					}
					if (!created) {
						created = true;
						facade.callRemote("getPlanElementsList", [], getElementsListHandler);
					}
					if (forceRedraw) {
						plan.userElements = userElements;
						plan.redraw();
					}
				}
			);
		}
		
		private function onShowAllChange(event:Event):void {
			if (plan) {
				plan.showAll = showAll.selected;
				plan.userElements = userElements;
				plan.redraw();
			}
		}
		
		private function setShowAllLabel():void {
			if (facade.locale.isReady()) {
				showAll.visible = true;
				showAll.label = facade.locale.translate("Show all elements");
				showAll.addEventListener(Event.CHANGE, onShowAllChange);
			} else {
				setTimeout(setShowAllLabel, 500);
			}
		}
	}
}